<template>
  <main-layout
    title="采购订单系统"
    :showHome="true"
    :showBack="false"
    :showNew="true"
    @newEvent="toNewPage"
    >
    <div class="inp-box">
      <input type="text" placeholder="输入项目名称进行查询" />
      <van-dropdown-menu class="purchase-dropdown">
        <van-dropdown-item
          v-model="queryObj.projectName"
          :options="stateList"
        />
      </van-dropdown-menu>
      <i class="icon"></i>
    </div>
    <ul @scroll="scrollEvt" class="ul-box">
      <li class="box" v-for="it in List" :key="it.id">
        <van-swipe-cell>
          <template #left>
            <van-button square type="primary" @click="toEdit(it)" text="详情" />
          </template>
          <span class="title"
            >{{ it.projectName }}
            <p class="em">{{ it.state }}</p>
          </span>
          <span class="role">创建人:{{ it.createId }}</span>
          <span class="role">创建日期:{{ it.createTime | fliter }}</span>
          <span class="role"
            >材料:{{
              `${it.materialName}-${it.materialWeight} ${it.materialUnit}`
            }}</span
          >
          <template #right>
            <van-button
              v-if="it.state === '新建'"
              square
              type="default"
              text="编辑"
            />
            <van-button
              v-if="it.state === '新建'"
              square
              type="danger"
              text="删除"
            />
            <van-button
              @click="approveEvt(it)"
              v-if="it.state === '新建'"
              square
              type="warning"
              text="确认"
            />
            <van-button
              @click="approveEvt(it)"
              v-if="it.state === '确认'"
              square
              type="info"
              text="在途"
            />
            <van-button
              @click="approveEvt(it)"
              v-if="it.state === '在途'"
              square
              type="primary"
              text="完成"
            />
            <van-button
              v-if="it.state === '完成'"
              square
              type="primary"
              text="付款"
            />
          </template>
        </van-swipe-cell>
      </li>
      <!-- 在系统中应该有以下：编辑和删除 -- 新增状态展示，并且只能是创建人操作 -->
      <!-- 确认按钮 -- 只能是选择的审批人有权限 -- 只能在新增状态 -->
      <!-- 在途(确认时显示)和完成(在途时展示)按钮 -- 只能是创建人可以操作 -->
      <!-- 付款按钮 -- 完成时展示 -->
    </ul>
    <section>
      {{ loading ? "加载中...." : hasMore ? "点击加载更多" : "带你点就打死你" }}
    </section>
    <!-- 弹出框 -->
    <van-popup
      v-model="show"
      close-icon-position="top-left"
      position="bottom"
      :style="{ height: '60%' }"
    >
      <p>审批意见</p>
      <van-steps :active="active">
        <van-step v-for="it in stepList" :key="it.text">{{ it.text }}</van-step>
      </van-steps>
      <van-form @submit="onSubmit">
        <van-field name="radio" label="是否同意">
          <template #input>
            <van-radio-group
              v-model="approveObj.isReject"
              direction="horizontal"
            >
              <van-radio checked-color="#ff5b02" :name="false">通过</van-radio>
              <van-radio checked-color="#ff5b02" :name="true">驳回</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="approveObj.userName"
          name="用户名"
          label="审批人"
          placeholder="输入审批人"
        />
        <van-field
          v-model="approveObj.remark"
          type="textarea"
          name="密码"
          label="审批意见"
          placeholder="输入审批意见"
          :rules="[{ required: true, message: '请输入审批意见' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
  </main-layout>
</template>
<script>
import { purchaseApi,purchFlow } from "../../apis/purch.js";
const stepList = [
  { text: "新建", value: "新建" },
  { text: "确认", value: "确认" },
  { text: "在途", value: "在途" },
  { text: "完成", value: "完成" },
];
export default {
  data() {
    return {
      List: [],
      stepList,
      stateList: [
        { text: "全部", value: "" },
        ...stepList,
        { text: "作废", value: "作废" },
      ],
      // 接口需要的参数
      queryObj: {
        projectName: "",
        state: "",
        page: 1,
        size: 6,
      },
      hasMore: true,
      loading: true,
      show: false,
      //   弹出框里面的
      stateContent: "",
      approveObj: {
        id: "",
        isReject: false,
        userId: "",
        userName: "",
        remark: "",
      },
    };
  },
  created() {
    //   页面创建出来 调用一次 获取列表信息
    this.getPuchaseList();
  },
  computed: {
    //   active 计算是从一开始的 进度条
    active() {
      return this.stepList.findIndex((it) => it.text === this.stateContent) + 1;
    },
    // 从状态管理器中拿到用户
    userInfo(){
        return this.$store.getters['common/userInfo']
    }
  },

  methods: {
    async getPuchaseList() {
      let result = await purchaseApi(this.queryObj);
      console.log(result);
      if (result.code === 200) {
        this.List = this.List.concat(result.data.rows);
        //  判断是否还有更多的数据
        this.hasMore =
          this.queryObj.page * this.queryObj.size < result.data.total;
      }
      setTimeout(() => {
        this.loading = false;
      });
    },
    scrollEvt(evt) {
      let isBottom =
        evt.target.offsetHeight + evt.target.scrollTop + 20 >
        evt.target.scrollHeight;
      //  节流 第一次请求未结束，不能请求第二次
      if (isBottom && !this.loading && this.hasMore) {
        this.queryObj.page += 1;
        this.loading = true;
        this.getPuchaseList();
      }
    },
    approveEvt(item) {
        console.log(this.userInfo)
      console.log("item", item);
    //   点开弹出框，重置内容
      this.approveObj.id=item.id
      this.approveObj.userName=this.userInfo.name
      this.approveObj.userId=this.userInfo.id
      this.approveObj.isReject=false
      this.approveObj.remark=''
      this.stateContent=item.state

      this.show = true;
    },
    async  onSubmit() {
      console.log("nihsizhu",this.approveObj);
      let result=await purchFlow(this.approveObj),
    //   返回当前的下标
      stateIndex=this.stepList.findIndex(it=>it.text===this.stateContent)+1
      console.log('返回当前的下标',stateIndex)
      if(result.code===200){
          this.$toast.success(`${this.stepList[stateIndex].text}成功`)
        //   通过
          if(!this.approveObj.isReject){
              this.List.map(it=>{
                //   更新列表数据
                  if(it.id===this.approveObj.id)  it.state=this.stepList[stateIndex].value
              })
            //   点击驳回
          }else{
              let idx=this.List.findIndex(it=>it.id===this.approveObj.id),nowIdx=stateIndex-2
              this.list[idx].state=this.stepList[nowIdx>=0?nowIdx:0].value
          }
      }else{
          this.$toast.fail(`${this.stepList[stateIndex].text}失败`)
      }

    },
    // 去详情页
    toEdit(it){
        console.log('it',it)
        this.$router.push({name:'detailPuc',query:{id:it.id,from:'puc'}})
    },
    //去新建页面
    toNewPage(){
      console.log("hahaha")
      this.$router.push({name:'editPuc',query:{from:'puc'}})
    }
  },
};
</script>

<style lang="less" scoped>
@import "../../style/common.less";
@import "../../style/index.less";
.inp-box {
  font-size: 0.7rem;
  padding: 4px 10px;
  display: flex;
  background: transparent;
  border-bottom: 1px solid @cdd;
  > input {
    flex: 1;
    border: none;
    background-color: transparent;
    outline: none;
    text-indent: 12px;
  }
  > .icon {
    flex: 0 0 48px;
    background: url("../../image/search-icon.png") center center/28px 28px
      no-repeat;
  }
}

section {
  color: @cdc;
  font-size: 0.7rem;
  padding: 0 30px;
}
.em {
  font-size: 0.7rem;
  color: rgb(247, 25, 25);
  display: inline-block;
}
</style>